package cn.com.yang.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Desc<AOP动态代理>
 * @Author 杨亿金
 * @Date 2021/1/19 10:39
 * @CopyRight
 * @Version
 */
public class DynamicProxy {
    interface IHello {
        void sayHello();
    }

    // alt + insert 快速实现方法
    static class Hello implements IHello {
        @Override
        public void sayHello() {
            System.out.println("hello world");
        }
    }

    static class DynamicProxyAop implements InvocationHandler {
        Object originalObj;

        Object bind(Object originalObj) {
            this.originalObj = originalObj;
            return Proxy.newProxyInstance(originalObj.getClass().getClassLoader(), originalObj.getClass().getInterfaces(), this);
        }

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            String className = originalObj.getClass().getName();
            System.out.println("welcome i am proxy:"+className);
            Object obj = method.invoke(originalObj, args);
            String mtName = method.getName();
            System.out.println(className+"."+mtName+" 执行完毕");
            return obj;
        }
    }

    public static void main(String[] args) {
        System.out.println( System.getProperties().getProperty("user.id"));
        System.out.println( System.getProperties().getProperty("user.home"));
        //生成反编译的动态代理代码
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles","true");
        IHello hello = (IHello) new DynamicProxyAop().bind(new Hello());
        hello.sayHello();
    }
}
